from rest_framework import serializers
from rest_framework.request import Request
from . import models
from . import forms
from ars import serializers as ars_serializers


class DutySerializer(serializers.ModelSerializer):

    def test(self):
        self.name = serializers.CharField(help_text="请在此填入Duty的ID参数，不是'name'")

    class Meta:
        model = models.Duty
        fields = "__all__"


class StatusSerializer(serializers.ModelSerializer):
    # status_code = serializers.CharField(style={'base_template': 'textarea.html'})

    class Meta:
        model = models.Status
        fields = ("status_code", "status_name", "status_type", "status_desc")

    def set_fields(self, *args):
        self.Meta.fields = args


class SiteSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Site
        fields = "__all__"


class OrgRoleSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.OrgRole
        fields = "__all__"


class OrgSerializer(serializers.ModelSerializer):
    # is_active = serializers.BooleanField(default=True)
    # create_date = serializers.DateTimeField()
    # manager = serializers.ReadOnlyField(source="test")
    manager = serializers.SerializerMethodField()
    manager_duty = serializers.SerializerMethodField()

    class Meta:
        model = models.Org
        fields = "__all__"
        # fields = ("org_name", "manager")

    def get_manager(self, obj):
        try:
            return obj.org_manager("user.last_name")
        except:
            return None

    def get_manager_duty(self, obj):
        try:
            return obj.org_manager("user.duty.name")
        except:
            return None


class UserSerializer(serializers.ModelSerializer):
    """
    显示单个用户的序列类，URL会传递ID值
    支持增删查改的操作
    """
    org = OrgSerializer(source="get_org_obj", many=True, read_only=True)  # 調用當前model的模型內置方法
    status = serializers.ReadOnlyField(source="status.status_name")
    # head = serializers.SerializerMethodField()

    class Meta:
        model = models.MyUser
        fields = ['id', 'org', 'site', 'status', 'last_login', 'first_name', 'last_name', 'email', 'username',
                  'date_joined', 'ext', 'short_number', 'mobile_phone', 'head', 'sign', 'entry_date', 'sex',
                  'duty', 'motto']
        read_only_fields = ('username', "last_login", 'date_joined', 'entry_date')

    # def get_head(self, obj):
    #     return "http://" + obj.head


class UsersSerializer(serializers.ModelSerializer):
    """
    显示所有用户信息的序列类，ID为链接形式，点击可访问单个User的信息
    支持查询操作
    """
    org = OrgSerializer(source="get_org_obj", many=True, read_only=True)        # 調用當前model的模型內置方法
    # site = SiteSerializer(required=False, read_only=False)
    # site = serializers.ModelField(model_field=models.Site())

    class Meta:
        model = models.MyUser
        extra_kwargs = {'password': {'write_only': True}}
        fields = ['id', 'org', 'site', 'status', 'last_login', 'username', 'first_name', 'last_name', 'email',
                  'date_joined', 'ext', 'short_number', 'mobile_phone', 'head', 'sign', 'password',
                  'entry_date', 'sex', 'duty', 'motto']
        read_only_fields = ("last_login", 'date_joined', 'head', 'sign', 'org')


class QueryUserSerializer(serializers.ModelSerializer):
    """
    显示所有用户信息的序列类，ID为链接形式，点击可访问单个User的信息
    支持查询操作
    """
    org = OrgSerializer(source="get_org_obj", many=True, read_only=True)        # 調用當前model的模型內置方法
    site = SiteSerializer(required=False, read_only=False)
    # site = serializers.ModelField(model_field=models.Site())

    class Meta:
        model = models.MyUser
        extra_kwargs = {'password': {'write_only': True}}
        fields = ['id', 'org', 'site', 'status', 'last_login', 'username', 'first_name', 'last_name', 'email',
                  'date_joined', 'ext', 'short_number', 'mobile_phone', 'head', 'sign', 'password',
                  'entry_date', 'sex', 'duty']
        read_only_fields = ("last_login", 'date_joined', 'head', 'sign', 'org')


class ProjectSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Project
        fields = "__all__"


class CheckSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.MyUser
        fields = ('username', 'password')


class OrgLevelsSerializer(serializers.ModelSerializer):
    level = serializers.CharField(help_text="請傳入父子兩個level值，以英文逗號分隔。增加頂級組織'0, max_level', "
                                            "增加末級組織'min_level, 0'", read_only=False)

    class Meta:
        model = models.OrgLevel
        fields = ('level', 'level_name', 'level_code')


class OrgLevelSerializer(serializers.ModelSerializer):
    level = serializers.CharField(help_text="請傳入父子兩個level值，以英文逗號分隔。增加頂級組織'0, max_level', "
                                            "增加末級組織'min_level, 0'", read_only=True)

    class Meta:
        model = models.OrgLevel
        fields = ('level', 'level_name', 'level_code')


class UserOrgRoleSerializer(serializers.ModelSerializer):
    """
    供显示用户的组织角色用
    """
    user = UserSerializer()
    org_role = serializers.SerializerMethodField()

    class Meta:
        model = models.UserOrgMap
        fields = ("user", "org_role")

    def get_org_role(self, obj):
        return obj.org_role.name


class UserOrgSerializer(serializers.ModelSerializer):
    # create_date = serializers.DateTimeField(format="%Y-%m-%D %H:%M:%S")

    class Meta:
        model = models.UserOrgMap
        fields = "__all__"


class BulkSerializer(serializers.ModelSerializer):
    """
    批量导入接口
    """
    class Meta:
        model = forms.BulkImport
        fields = "__all__"


class LoginQRCodeSerializer(serializers.ModelSerializer):
    """
    二维码登录接口（app:记录uid和工号，web:返回用户信息）
    """
    type = serializers.ChoiceField(('app', 'web'))

    class Meta:
        model = models.QRCode
        fields = ('uid', 'username', 'type')


class RetrievePWDSerializer(serializers.ModelSerializer):
    """
    填写工号和邮箱，系统验证通过后自动发出重置密码的验证码
    """

    class Meta:
        model = forms.RetrievePWDForm
        fields = "__all__"


class SetNewPWDSerializer(serializers.ModelSerializer):
    """
    使用邮箱中提供的验证码进行密码的修改操作
    """
    class Meta:
        model = forms.SetNewPWDForm
        fields = "__all__"


class ActiveUserSerializer(serializers.ModelSerializer):
    """
    修改用戶狀態
    """
    class Meta:
        model = forms.ActiveUserForm
        fields = "__all__"


class UpdatePWDSerializer(serializers.ModelSerializer):
    """
    Update user password
    """

    class Meta:
        model = forms.UpdatePWDForm
        fields = "__all__"